package com.xingkeduo.controller.base;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.util.CollectionUtils;

import com.xingkeduo.model.param.ActivityDaysParam;
import com.xingkeduo.model.param.MarketingParam;
import com.xingkeduo.model.param.MarketingParam.MarketingReceiveTypeEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingRefundTypeEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingServiceTypeEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingTypeEnum;
import com.xingkeduo.model.param.MarketingRelevantParam;
import com.xingkeduo.model.param.common.BaseParam;
import com.xingkeduo.util.Constant;
import com.xingkeduo.util.StringUtils;
import com.xingkeduo.util.pojo.exception.DataException;
import com.xingkeduo.util.tool.ResponseMessage;

public class MarketingBaseController extends InitController {
	protected void initParams(BaseParam baseParam) {
		super.initUserInParams(baseParam);
		ResponseMessage checkResult = checkRequestParam(baseParam);
		if (checkResult.getStatus() != ResponseMessage.ok().getStatus()) {
			throw new DataException(DataException.Type.FAIL, checkResult.getMsg());
		}
	}

	protected ResponseMessage checkRequestParam(BaseParam baseParam) {
		MarketingParam marketingParam = (MarketingParam) baseParam;
		String marketingType = MarketingTypeEnum.parseStatus(marketingParam.getMarketingType()).getDesc();
		if (!marketingParam.getMarketingType().equals(MarketingTypeEnum.COUPON_BAG.getCode())
				&& StringUtils.isBlank(marketingParam.getServiceType())) {
			return ResponseMessage.error(marketingType + "类型缺失", 500);
		}
		if (StringUtils.isBlank(marketingParam.getName())) {
			return ResponseMessage.error(marketingType + "名称缺失", 500);
		}
		if (marketingParam.getReceiveType() == null) {
			marketingParam.setReceiveType(MarketingReceiveTypeEnum.ALL.getCode());
		}
		if (marketingParam.getReceiveType() != null
				&& MarketingReceiveTypeEnum.PLATFORM_NEW.getCode() != marketingParam.getReceiveType()
				&& MarketingReceiveTypeEnum.ALL.getCode() != marketingParam.getReceiveType()) {
			return ResponseMessage.error(marketingType + "领取范围（星客多普通用户，星客多新用户）", 500);
		}
		if (marketingParam.getLeastCost() == null) {
			marketingParam.setLeastCost(BigDecimal.valueOf(0));
		}
		if (marketingParam.getLeastCost().compareTo(BigDecimal.valueOf(0)) < 0
				|| marketingParam.getLeastCost().compareTo(BigDecimal.valueOf(100000)) > 0) {
			return ResponseMessage.error("使用门槛范围0.01～100000", 500);
		}
		if ((!marketingParam.getMarketingType().equals(MarketingTypeEnum.COUPON_BAG.getCode()))
				&& StringUtils.isBlank(marketingParam.getSupportServprodIds())) {
			marketingParam.setSupportServprodIds("0");
			marketingParam.setSupportServprodNames("支持所有服务");
		}
		if (marketingParam.getCouponAmount() == null) {
			marketingParam.setCouponAmount(BigDecimal.valueOf(0));
		}
		if (marketingParam.getCouponAmount().compareTo(BigDecimal.valueOf(0)) < 0) {
			return ResponseMessage.error(marketingType + "面额小于0", 500);
		}
		if ((!marketingParam.getMarketingType().equals(MarketingTypeEnum.COUPON_BAG.getCode()))
				&& marketingParam.getServiceType().equals(MarketingServiceTypeEnum.DISCOUNT.getType())
				&& marketingParam.getCouponAmount().compareTo(BigDecimal.valueOf(10)) > 0) {
			return ResponseMessage.error("折扣面额超过10折", 500);
		}
		if ((!marketingParam.getMarketingType().equals(MarketingTypeEnum.COUPON_BAG.getCode()))
				&& marketingParam.getServiceType().equals(MarketingServiceTypeEnum.DISCOUNT.getType())) {
			marketingParam.setCouponAmount(marketingParam.getCouponAmount().divide(BigDecimal.valueOf(10), 2, BigDecimal.ROUND_HALF_DOWN));
		}
		if (marketingParam.getStockQuantity() == null || marketingParam.getStockQuantity().intValue() < 1
				|| marketingParam.getStockQuantity().intValue() > 10000000) {
			return ResponseMessage.error("库存范围为1～10,000,000张", 500);
		}
		if (marketingParam.getGetLimitDay() == null) {
			marketingParam.setGetLimitDay(0);
		}
		if (marketingParam.getGetLimitDay().intValue() < 0 || marketingParam.getGetLimitDay().intValue() > 1000) {
			return ResponseMessage.error("单日领取范围为1～1000张", 500);
		}
		if (marketingParam.getGetLimitTotal() == null) {
			marketingParam.setGetLimitTotal(0);
		}
		if (marketingParam.getGetLimitTotal().intValue() < 0 || marketingParam.getGetLimitTotal().intValue() > 1000) {
			return ResponseMessage.error("累积领取范围为1～1000张", 500);
		}
		if ((!marketingParam.getMarketingType().equals(MarketingTypeEnum.COUPON_BAG.getCode()))
				&& StringUtils.isBlank(marketingParam.getStoreIds())) {
			marketingParam.setStoreIds("0");
			marketingParam.setStoreNames("适用所有门店");
		}
		if ((!marketingParam.getMarketingType().equals(MarketingTypeEnum.COUPON_BAG.getCode()))
				&& marketingParam.getUseType() == null) {// 相对时间
			return ResponseMessage.error("请选择可用日期类型", 500);
		}
		if ((!marketingParam.getMarketingType().equals(MarketingTypeEnum.COUPON_BAG.getCode()))
				&& marketingParam.getUseType().intValue() == 0 && marketingParam.getUsePeriod() == null) {// 相对时间
			return ResponseMessage.error("请填写使用有效期", 500);
		}
		if ((!marketingParam.getMarketingType().equals(MarketingTypeEnum.COUPON_BAG.getCode()))
				&& marketingParam.getUseType().intValue() == 1
				&& (marketingParam.getUseStartTime() == null || marketingParam.getUseEndTime() == null)) {// 相对时间
			return ResponseMessage.error("请填写使用起止日期", 500);
		}
		if ((!marketingParam.getMarketingType().equals(MarketingTypeEnum.COUPON_BAG.getCode()))
				&& marketingParam.getUseLimitDay() == null) {
			marketingParam.setUseLimitDay(0);
		}
		if ((!marketingParam.getMarketingType().equals(MarketingTypeEnum.COUPON_BAG.getCode()))
				&& (marketingParam.getUseLimitDay().intValue() < 0
						|| marketingParam.getUseLimitDay().intValue() > 1000)) {
			return ResponseMessage.error("单日使用范围为1～1000张", 500);
		}
		if ((!marketingParam.getMarketingType().equals(MarketingTypeEnum.COUPON_BAG.getCode()))
				&& marketingParam.getUseLimitTotal() == null) {
			marketingParam.setUseLimitTotal(0);
		}
		if ((!marketingParam.getMarketingType().equals(MarketingTypeEnum.COUPON_BAG.getCode()))
				&& (marketingParam.getUseLimitTotal().intValue() < 0
						|| marketingParam.getUseLimitTotal().intValue() > 1000)) {
			return ResponseMessage.error("累积使用范围为1～1000张", 500);
		}
		if ((!marketingParam.getMarketingType().equals(MarketingTypeEnum.COUPON_BAG.getCode()))
				&& StringUtils.isBlank(marketingParam.getWeekHourIds())) {
			marketingParam.setWeekHourIds("0");
		}
		if (marketingParam.getMarketingType().equals(MarketingTypeEnum.COUPON.getCode())
				&& (marketingParam.getRefundType() == null || MarketingRefundTypeEnum
						.parseStatus(marketingParam.getRefundType()).equals(MarketingRefundTypeEnum.UNKNOWN))) {
			return ResponseMessage.error("退款规则不合法", 500);
		}
		if (marketingParam.getMarketingType().equals(MarketingTypeEnum.COUPON_BAG.getCode())
				&& StringUtils.isBlank(marketingParam.getSubTitle())) {
			return ResponseMessage.error("请填写券包副标题", 500);
		}
		if (marketingParam.getIsOpenConvert() == null) {
			marketingParam.setIsOpenConvert(0);
		}
		if(StringUtils.isNotBlank(marketingParam.getStoreIds())) {
			String storeIds = com.xingkeduo.util.BeanUtils.buildStartAndEndWithZero(marketingParam.getStoreIds());
			marketingParam.setStoreIds(storeIds);
		}
		String supportServprodIds = com.xingkeduo.util.BeanUtils
				.buildStartAndEndWithZero(marketingParam.getSupportServprodIds());
		marketingParam.setSupportServprodIds(supportServprodIds);
		String dayIds = buildDaysStartAndEndWithZero(marketingParam.getActivityDaysParams());
		marketingParam.setWeekHourIds(dayIds);
		if(marketingParam.getMarketingType().equals(MarketingTypeEnum.COUPON_BAG.getCode())) {
			String relevantIds = buildRelevantStartAndEndWithZero(marketingParam.getMarketingRelevantParams());
			marketingParam.setSupportMarketingIds(relevantIds);
		}
		if(StringUtils.isBlank(marketingParam.getBannerUrl())) {
			marketingParam.setBannerUrl(Constant.MARKETING_BANNER_URL);
		}
		if(marketingParam.getReceiveStartTime()!=null && marketingParam.getReceiveEndTime() !=null
				&& marketingParam.getReceiveStartTime().after(marketingParam.getReceiveEndTime())) {
			return ResponseMessage.error("领取开始时间不能大于结束时间", 500);
		}
		if(marketingParam.getUseStartTime()!=null && marketingParam.getUseEndTime() !=null
				&& marketingParam.getUseStartTime().after(marketingParam.getUseEndTime())) {
			return ResponseMessage.error("使用开始时间不能大于结束时间", 500);
		}
		if(marketingParam.getSellEnable()==null) {
			marketingParam.setSellEnable(Constant.STATUS_NO);
		}
		if(StringUtils.isNotBlank(marketingParam.getSellStoreIds())) {
			String sellStoreIds = com.xingkeduo.util.BeanUtils.buildStartAndEndWithZero(marketingParam.getSellStoreIds());
			marketingParam.setSellStoreIds(sellStoreIds);
		}
		return ResponseMessage.ok();
	}

	private String buildRelevantStartAndEndWithZero(List<MarketingRelevantParam> marketingRelevantParams) {
		String str = "0";
		if (CollectionUtils.isEmpty(marketingRelevantParams)) {
			throw new RuntimeException("请选择优惠优惠包支持的券或卡");
		}
		StringBuffer relevantIdsBuffer = new StringBuffer();
		for (int i = 0; i < marketingRelevantParams.size(); i++) {
			MarketingRelevantParam relevant = marketingRelevantParams.get(i);
			if (relevant.getSupportBusinessId() == null || StringUtils.isBlank(relevant.getServprodName())
					|| StringUtils.isBlank(relevant.getMarketingServiceType())) {
				throw new RuntimeException("请选择优惠优惠包支持的券或卡");
			}
			relevantIdsBuffer.append(relevant.getSupportBusinessId()).append(",");
		}
		str = com.xingkeduo.util.BeanUtils.removerepeatedchar(relevantIdsBuffer.toString()).replaceAll(",,", ",");
		return com.xingkeduo.util.BeanUtils.buildStartAndEndWithZero(str);
	};

	private static String buildDaysStartAndEndWithZero(List<ActivityDaysParam> activityDaysParams) {
		String str = "0";
		if (CollectionUtils.isEmpty(activityDaysParams)) {
			return str;
		}
		StringBuffer dayIdsBuffer = new StringBuffer();
		for (int i = 0; i < activityDaysParams.size(); i++) {
			ActivityDaysParam days = activityDaysParams.get(i);
			if (StringUtils.isBlank(days.getDayids()) || days.getStartTime() == null || days.getStartTime() == null) {
				throw new RuntimeException("请选择优惠时间段");
			}
			if (days.getStartTime().after(days.getEndTime())) {
				throw new RuntimeException("优惠开始时间必须小于结束时间");
			}
			String daysStr = days.getDayids().replaceAll(",,", ",");
			if (daysStr.startsWith(",")) {
				daysStr = daysStr.substring(1, daysStr.length());
			}
			if (daysStr.endsWith(",")) {
				daysStr = daysStr.substring(0, daysStr.length() - 1);
			}
			days.setDayids(daysStr);
			dayIdsBuffer.append(daysStr).append(",");
			
		}
		str = com.xingkeduo.util.BeanUtils.removerepeatedchar(dayIdsBuffer.toString()).replaceAll(",,", ",");
		if (str.endsWith(",")) {
			str = str.substring(0, str.length() - 1);
		}
		return str;
	}
}
